<template>
  <div id="userManagePage">
    <!-- 搜索表单 -->
    <a-form ref="formRef" layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="账号" name="userAccount">
        <a-input v-model:value="searchParams.userName" placeholder="输入账号" allow-clear />
      </a-form-item>
      <a-form-item label="邮箱" name="userName">
        <a-input v-model:value="searchParams.email" placeholder="输入邮箱" allow-clear />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="resetSearch">重置</a-button>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-space>

      </a-form-item>
    </a-form>
    <div style="margin-bottom: 16px"></div>
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      :loading="loading"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.avatar" width="120px" />
        </template>
        <template v-if="column.dataIndex === 'userRole'">
          <div class="editable-cell">
            <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
              <a-select
                v-model:value="editableData[record.key].userRole"
                mode="multiple"
                style="width: 100%"
                placeholder="Please select"
                :options="GET_ACCESS_MAP_OPTIONS"
              ></a-select>
              <check-outlined class="editable-cell-icon-check" @click="saveed(record.key)" />
            </div>
            <div v-else class="editable-cell-text-wrapper">
              <a-space wrap>
                <div v-for="role in record.userRole" :key="role">
                  <a-tag :color="GET_ACCESS_MAP_OPTION(role).color">{{ GET_ACCESS_MAP_OPTION(role).value }}</a-tag>
                </div>
              </a-space>
              <edit-outlined class="editable-cell-icon" @click="edited(record.key)" />
            </div>
          </div>
        </template>
        <template v-if="column.dataIndex === 'status'">
          <div v-if="record.status === 0">
            <a-tag color="green">启用</a-tag>
          </div>
          <div v-else>
            <a-tag color="blue">禁用</a-tag>
          </div>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'updateTime'">
          {{ dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'nickName'">
          <div class="editable-cell">
            <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
              <a-input
                v-model:value="editableData[record.key].nickName"
                @pressEnter="save(record.key)"
              />
              <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
            </div>
            <div v-else class="editable-cell-text-wrapper">
              {{ text || ' ' }}
              <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
            </div>
          </div>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button v-if="record.status === 1" @click="ChangeStatus(record,0)">启用</a-button>
            <a-button v-if="record.status === 0" @click="ChangeStatus(record,1)">停用</a-button>
            <a-button type="link" :href="`/user/add_user?id=${record.id}`" target="_blank">编辑</a-button>
            <a-popconfirm title="你确定要删除吗?" @confirm="doDelete(record.id)">
              <a-button danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue'
import { computed, onMounted, reactive, ref, type UnwrapRef } from 'vue'
import {
  deleteUserUsingPost,
  listUserVoByPageUsingPost, updateUserStatusUsingPost,
  updateUserUsingPost
} from '@/api/authUserController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'
import {
  GET_ACCESS_MAP_OPTION, GET_ACCESS_MAP_OPTIONS

} from '../../access/accessEnum.ts'

interface DataItem {
  nickName: string
  userRole: string[];
}

const columns = [
  {
    title: 'id',
    dataIndex: 'id'
  },
  {
    title: '账号',
    dataIndex: 'userName'
  },
  {
    title: '用户名',
    dataIndex: 'nickName'
  },
  {
    title: '头像',
    dataIndex: 'userAvatar'
  },
  {
    title: '状态',
    dataIndex: 'status'
  },
  {
    title: '用户角色',
    dataIndex: 'userRole'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime'
  },
  {
    title: '操作',
    key: 'action'
  }
]

// const selectedUserRoles = ref([])
const dataList = ref<API.AuthUserVO[]>([])
const total = ref(0)
const searchParams = reactive<API.AuthUserQueryDTO>({
  current: 1,
  pageSize: 10,
  sortField: 'create_time',
  sortOrder: 'ascend'
})
const loading = ref(false)
const fetchData = async () => {
  try {
    loading.value = true
    const res = await listUserVoByPageUsingPost({
      ...searchParams
    })
    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data.records.map((item) => ({
        ...item,
        key: item.id,
        userRole: item.userRole ? item.userRole.split(',').map(role => role.trim()) : []
      }))
      total.value = res.data.data.total ?? 0
    } else {
      message.error('获取数据失败: ' + res.data.message)
    }
  } catch (error) {
    message.error('请求失败: ' + error)
  }
  console.log('展示sssssssssssssssssss')
  loading.value = false
}

const editableData: UnwrapRef<Record<string, DataItem>> = reactive({})

const edit = (key: string) => {
  const record = dataList.value.find((item) => item.key === key)
  if (record) {
    editableData[key] = cloneDeep(record)
  }
}
const save = async (key: string) => {
  const record = dataList.value.find((item) => item.key === key)
  if (record) {
    Object.assign(record, editableData[key])
    const res = await updateUserUsingPost(record)
    //注册成功，跳转登录页面
    if (res.data.code === 0) {
      delete editableData[key]
      fetchData()
    } else {
      message.error('修改失败: ' + res.data.message)
    }
  }
}

const formRef = ref()
// 重置搜索栏

const resetSearch = () => {
  formRef.value.resetFields()
  doSearch()
}

onMounted(() => {
  fetchData()
})

const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: +total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共${total}条`
  }
})

const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

const doSearch = () => {
  searchParams.current = 1
  fetchData()
}

const doDelete = async (id: string) => {
  if (!id) {
    return
  }
  try {
    const res = await deleteUserUsingPost({ id })
    searchParams.current =
      total.value % searchParams.pageSize == 1
        ? searchParams.current - 1
        : searchParams.current
    if (res.data.code === 0) {
      message.success('删除成功')
      fetchData()
    } else {
      message.error('删除失败: ' + res.data.message)
    }
  } catch (error) {
    message.error('请求失败: ' + error)
  }
}

//获取用户权限
const userRoleArray = (userRole: string[]) => {
  return userRole.map(key => GET_ACCESS_MAP_OPTION(key).value)
}
//修改状态
const ChangeStatus = async (record: any, status: number) => {
  if (!record.id) {
    return
  }
  const id = record.id
  if (!id) {
    return
  }
  try {
    const res = await updateUserStatusUsingPost({ id, status })
    if (res.data.code === 0 && res.data.data) {
      message.success('修改成功')
      fetchData()
    } else {
      message.error('修改失败: ' + res.data.message)
    }
  } catch (e) {
    message.error('请求失败: ' + e)
  }
}

const edited = (key: string) => {
  const record = dataList.value.find((item) => item.key === key)
  if (record) {
    editableData[key] = {
      ...record,
      userRole: record.userRole
    }
  }
}

const saveed = async (key: string) => {
  const record = dataList.value.find((item) => item.key === key)
  if (record) {
    const userRoleKeys = editableData[key].userRole.join(',')
    Object.assign(record, {
      ...editableData[key],
      userRole: userRoleKeys
    })
    const res = await updateUserUsingPost(record)
    if (res.data.code === 0) {
      // 更新 dataList 中的记录
      const index = dataList.value.findIndex(item => item.key === key);
      if (index !== -1) {
        dataList.value[index] = { ...dataList.value[index], userRole: editableData[key].userRole };
      }
      delete editableData[key]
      fetchData()
    } else {
      message.error('修改失败: ' + res.data.message)
    }
  }
}
</script>

<style lang="less" scoped>
.editable-cell {
  position: relative;

  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>
